<template>
  <div ref="echartsRef" :style="{ width: props.width, height: props.height }"></div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, onUnmounted, ref, watch, nextTick } from 'vue';
import type { ECharts, EChartsOption } from 'echarts';
import type { EChartsData } from '@/store/modules/earlyWarning/useThirdPartyRiskStore';

interface Props {
  echartsData: EChartsData | null;
  height?: string;
  width?: string;
}

const props = withDefaults(defineProps<Props>(), {
  height: '100%',
  width: '100%'
});

const emit = defineEmits<{
  (event: 'thirdPartyClick', params: unknown): void;
}>();

const echartsRef = ref<HTMLElement | null>(null);
const myChart = ref<ECharts | null>(null);
let resizeObserver: ResizeObserver | null = null;

// 生成图表配置
const generateChartOption = (echartsData: EChartsData): EChartsOption => {
  const xItem = echartsData.xaxisList[0].data;
  const seriesData = echartsData.seriesList.map(
    (item) =>
      ({
        ...item,
        barWidth: '10%',
        itemStyle: {
          barBorderRadius: [10, 10, 0, 0] as const,
          color: new echarts.graphic.LinearGradient(
            0,
            0,
            0,
            1,
            [
              { offset: 0, color: 'rgba(5, 213, 255, 1)' },
              { offset: 1, color: 'rgba(5, 213, 255, 0)' }
            ],
            false
          ),
          shadowColor: 'rgba(5, 213, 255, 1)',
          shadowBlur: 4
        },
        label: {
          show: true,
          lineHeight: 10,
          formatter: '{c}',
          position: 'top',
          color: '#fff',
          fontSize: 10
        },
        type: 'bar'
      }) as echarts.SeriesOption
  ); // 显式类型转换

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    grid: {
      top: '15%',
      right: '6%',
      left: '10%',
      bottom: '20%'
    },
    xAxis: {
      type: 'category',
      data: xItem,
      axisLine: {
        lineStyle: { color: 'rgba(66, 192, 255, .3)' }
      },
      axisLabel: {
        interval: 0,
        rotate: 30,
        margin: 10,
        color: '#05D5FF',
        fontSize: 11
      },
      axisTick: { show: false },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#0a3f86',
          type: 'dashed'
        }
      }
    },
    yAxis: {
      axisLabel: {
        padding: [3, 0, 0, 0],
        formatter: '{value}',
        color: 'rgba(95, 187, 235, 1)',
        fontSize: 11
      },
      axisTick: { show: true },
      axisLine: {
        lineStyle: { color: 'rgba(66, 192, 255, .3)' }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#0a3f86',
          type: 'dashed'
        }
      }
    },
    series: seriesData
  };
};

// 初始化图表
const initChart = () => {
  if (!echartsRef.value) return;

  disposeChart();
  myChart.value = echarts.init(echartsRef.value);
  updateChart();
};

// 更新图表数据
const updateChart = () => {
  if (!myChart.value || !props.echartsData) return;

  const option = generateChartOption(props.echartsData);
  myChart.value.setOption(option);

  // 移除旧事件监听器并添加新的
  myChart.value.off('click');
  myChart.value.on('click', (params) => {
    emit('thirdPartyClick', params);
  });
};

// 销毁图表
const disposeChart = () => {
  if (myChart.value && !myChart.value.isDisposed()) {
    myChart.value.dispose();
  }
  myChart.value = null;
};

// 处理窗口大小变化
const handleResize = () => {
  nextTick(() => {
    if (myChart.value && !myChart.value.isDisposed()) {
      myChart.value.resize();
    }
  });
};

// 使用 ResizeObserver 监听容器大小变化
const initResizeObserver = () => {
  if (!echartsRef.value) return;

  resizeObserver = new ResizeObserver(() => {
    handleResize();
  });
  resizeObserver.observe(echartsRef.value);
};

// 生命周期钩子
onMounted(() => {
  initChart();
  initResizeObserver();
});

onUnmounted(() => {
  if (resizeObserver) {
    resizeObserver.disconnect();
    resizeObserver = null;
  }
  disposeChart();
});

// 监听数据变化
watch(
  () => props.echartsData,
  () => {
    updateChart();
  },
  { deep: true }
);

// 监听容器尺寸变化
watch(
  () => [props.width, props.height],
  () => {
    handleResize();
  }
);
</script>
